package utils;



import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/** 管理员长连接单例 */
public class AdminConnection {
    private static Socket socket;
    private static PrintWriter out;
    private static BufferedReader in;
    private static volatile boolean running = false;
    private static final BlockingQueue<String> sendQueue = new LinkedBlockingQueue<>();

    /** 线程安全地启动唯一连接 */
    public static void start(String adminName) throws IOException {
        if (running) return;
        synchronized (AdminConnection.class) {
            if (running) return;
            socket = new Socket("localhost", 8888);
            out  = new PrintWriter(socket.getOutputStream(), true);
            in   = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out.println("IAMAdmin:" + adminName);
            running = true;

            Thread t = new Thread(() -> {
                try {
                    String line;
                    while (running) {
                        /* 1. 读服务器 */
                        if (in.ready() && (line = in.readLine()) != null) {
                            if (line.startsWith("SYS:")) {
                                System.out.println("【系统】" + line.substring(4));
                            } else if (line.startsWith("CHAT:")) {
                                String[] a = line.split(":", 4);
                                System.out.println("【" + a[1] + "】" + a[3]);
                            }
                        }
                        /* 2. 发送队列 */
                        String toSend;
                        while ((toSend = sendQueue.poll()) != null) {
                            out.println(toSend);
                        }
                        Thread.sleep(100);   // 防止 CPU 飙满
                    }
                } catch (Exception ignore) {}
                finally { close(); }
            }, "user-reader");
            t.setDaemon(true);
            t.start();
        }
    }
    public static PrintWriter getWriter() { return out; }
    public static BufferedReader getReader() { return in; }
    public static void send(String msg) { sendQueue.offer(msg); }
    public static void close() {
        running = false;
        try { if (socket != null) socket.close(); } catch (IOException ignore) {}
    }
}